import logging
from logging import debug
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)

import scipy.io as sio

import numpy as np
from matplotlib.dates import date2num

from read_from_h5 import load_data

"""
Functions used to export pytables to matlab mat files
"""
def get_clean_array(data, sel_tbs=None):
    all_tbs = data.dtype.names
    if not sel_tbs:
        sel_tbs = all_tbs
    arr_data = np.array([data[sel_tbs[0]]]).T
    debug(arr_data)
    for tb in sel_tbs[1:]:
        arr_data = np.append(arr_data, np.array([data[tb]]).T, 1)

    return arr_data


def write_arr_to_mat(arr):
    sio.savemat('./arrdata.mat', mdict={'arr': arr})
    return


def file_to_soren(data):
    sel_tags = ["rotorrpmavg",
                "bladespitchangleavg",
                "windspeedavg",
                "time",
                "activepoweravg"]
    sel_tags = sorted(sel_tags)
    arr = get_clean_array(data, sel_tags)
    write_arr_to_mat(arr)
    return


def main():
    turbid = "WH1108"
    h5_file = "../../h5data/wh1.h5"
    filt_strings = ["(activepoweravg > 0)",
                    "(activepoweravg < 2200)",
                    "(time >= " + str(date2num(datetime.datetime(2000, 01, 01))) + " )",
                    #"(time <= " + str(date2num(datetime.datetime(2012,01,01))) + " )"]
                    "(time <= " + str(date2num(datetime.datetime(2012, 01, 01))) + " )",
                    "(turbid == '" + turbid + "' )"]
    debug(filt_strings)

    data = load_data(h5_file, filt=filt_strings)
    file_to_soren(data)


if __name__ == "__main__":
    main()

